package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.mysql.jdbc.Connection;
import lombok.SneakyThrows;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author shkstart
 * 让阅读量
 * @create 2023-01-12-23:09
 */
@WebServlet("/addrcount")
public class AddReadCountServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String msg = "位置的参数addreadcountservlet";
        int data = 0;
        //1.拿到参数进行校验
        String aidstr = req.getParameter("aid");
        if (!StrUtil.isBlank(aidstr)) {//让阅读量+1
            int aid = Integer.valueOf(aidstr);
            if (aid > 0) {
                //得到连接
                Connection connection = DBUtils.getConnection();
                //拼接sql
                String sql = "update article set readcount = readcount+1 where aid = ?";
                PreparedStatement statement = connection.prepareStatement(sql);

                //执行执行器，得到结果
                statement.setInt(1, aid);
                data = statement.executeUpdate();//返回受影响的行数
                //关闭资源
                DBUtils.close(null,statement,connection);
            }
            msg = "成功抵达";
        } else {
            msg = "参数aid 错误";
        }
        //返回给前端
        resp.setContentType(AppVar.RESP_JSON_UTF8);
        resp.getWriter().println(
                JSONUtil.toJsonStr(
                        ResultUtils.toResult(200, data, msg)
                )
        );
    }
}
